<template>
  <div class="app-container">
    <!--form 组件-->
    <eForm ref="form" :is-add="isAdd" :dicts="dicts"/>
    <import-user ref="importForm" :importDept="importDept" ></import-user>
    <update-user-pass ref="updateUserFrom"></update-user-pass>
    <el-row :gutter="20">
      <!--部门数据-->
<!--      <el-col :xs="9" :sm="8" :md="6" :lg="6" :xl="6">
        <div class="head-container">
          <el-input v-model="deptName" clearable placeholder="输入部门名称搜索" maxlength="10" prefix-icon="el-icon-search" style="width: 100%;" class="filter-item" @input="getDeptDatas"/>
        </div>
        <div class="bs-Tree dd-tree ">
         <el-tree :data="depts" :props="defaultProps" :expand-on-click-node="false" node-key="id" :default-expanded-keys="expanded" @node-click="handleNodeClick"/>
       </div> -->
      </el-col>
      <!--用户数据-->
      <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
     <!-- <el-col :xs="15" :sm="16" :md="18" :lg="18" :xl="18"> -->
        <!--工具栏-->
        <div class="head-container">
          <!-- 搜索 -->
          <el-input v-model="query.value" clearable placeholder="输入关键字搜索" maxlength="10" style="width: 200px;" class="filter-item" @keyup.enter.native="toQuery"/>
          <el-select v-model="query.type" clearable placeholder="搜索字段" class="filter-item" style="width: 130px">
            <el-option v-for="item in queryTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
          </el-select>
          <!-- <el-select v-model="query.enabled" clearable placeholder="状态" class="filter-item" style="width: 90px" @change="toQuery">
            <el-option v-for="item in enabledTypeOptions" :key="item.key" :label="item.display_name" :value="item.key"/>
          </el-select> -->
          <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="toQuery">搜索</el-button>
          <!-- 新增 -->
          <!-- <div v-permission="['ADMIN','USER_ALL','USER_CREATE']" style="display: inline-block;margin: 0px 2px;">
            <el-button
              class="filter-item"
              size="mini"
              type="primary"
              icon="el-icon-plus"
              @click="add">新增</el-button>
          </div> -->
          <!-- 导出 -->
         <!-- <div style="display: inline-block;">
            <el-button
              v-permission="['ADMIN']"
              :loading="downloadLoading"
              size="mini"
              class="filter-item"
              type="warning"
              icon="el-icon-download"
              @click="download">导出</el-button>
              <el-button
                v-permission="['ADMIN']"
                :loading="downloadLoading"
                size="mini"
                class="filter-item"
                type="success"
                icon="el-icon-upload"
                @click="toImport()">导入</el-button>
                <el-button
                  v-permission="['ADMIN']"
                  :loading="downloadLoading"
                  size="mini"
                  class="filter-item"
                  type="success"
                  icon="el-icon-download"
                  @click="downloadTemp()">模板下载</el-button>
          </div> -->
        </div>
        <!--表格渲染-->
        <el-table v-loading="loading" :data="data" size="small" style="width: 100%;" border>
          <el-table-column type="index" label="序号" align="center" width="60"/>
          <el-table-column prop="name" label="姓名" align="center" width="140"/>
          <el-table-column prop="username" label="账号" align="center" width="140"/>
          <el-table-column prop="userNumber" label="用户编号" align="center"  width="200" />
          <el-table-column prop="sex" label="性别" align="center"  width="140"/>
          <el-table-column prop="age" label="年龄" align="center"  width="140" />
          <el-table-column prop="phone" label="联系电话" align="center" />
          <el-table-column label="所属部门" align="center">
            <template slot-scope="scope">
              <div>{{ scope.row.deptName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="权限" align="center" width="160">
            <template slot-scope="scope">
              <div>
                <el-tag
                  v-for="(tag,index) in scope.row.roles"
                  :key="tag.index"
                  :type="tag.id">
                  {{tag.name}}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" width="120">
            <template slot-scope="scope">
              <div v-for="item in dicts" :key="item.id">
                <el-tag v-if="scope.row.enabled.toString() === item.value" :type="scope.row.enabled ? '' : 'info'">{{ item.label }}</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column :show-overflow-tooltip="true" prop="createTime" label="创建日期" align="center">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
            </template>
          </el-table-column>
          <el-table-column v-if="checkPermission(['ADMIN','USER_ALL','USER_EDIT','USER_DELETE'])" label="操作" width="340" align="center">
            <template slot-scope="scope">
              <el-button :disabled="scope.row.show" v-permission="['ADMIN','USER_ALL','USER_EDIT']" size="mini"  type="primary" icon="el-icon-edit" @click="edit(scope.row)">修改</el-button>
              <el-popover
                v-permission="['ADMIN','USER_ALL','USER_DELETE']"
                :ref="scope.row.id"
                placement="top"
                width="180">
                <p>是否删除该账号！</p>
                <div style="text-align: right; margin: 0">
                  <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
                  <el-button :loading="delLoading" type="primary" size="mini" @click="subDelete(scope.row.id)">确定</el-button>
                </div>
                <el-button :disabled="scope.row.show"  slot="reference" type="danger" icon="el-icon-delete" size="mini">删除</el-button>
              </el-popover>
              <el-button :disabled="scope.row.show" v-if="scope.row.enabled" v-permission="['ADMIN','USER_ALL','USER_RESET']" :loading="resetLoading" size="mini" type="warning"
              icon="el-icon-refresh" @click="suspensionUser(scope.row.id,false)">封停</el-button>
              <el-button :disabled="scope.row.show" v-if="!scope.row.enabled" v-permission="['ADMIN','USER_ALL','USER_RESET']" :loading="resetLoading" size="mini" type="warning"
              icon="el-icon-refresh" @click="suspensionUser(scope.row.id,true)">解封</el-button>
              <el-button :disabled="scope.row.show" style="margin-left: 0px;" v-permission="['ADMIN','USER_ALL','USER_RESET']" size="mini" type="success" icon="el-icon-edit-outline" @click="upUserPass(scope.row)">修改密码</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <el-pagination
          :total="total"
          :current-page="page + 1"
          style="margin-top: 8px;"
          layout="total, prev, pager, next, sizes"
          @size-change="sizeChange"
          @current-change="pageChange"/>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { suspension } from '@/api/framework/system/user'
import checkPermission from '@/utils/permission'
import initData from '@/mixins/initData'
import initDict from '@/mixins/initDict'
import { del, reset } from '@/api/framework/system/user'
import { getDepts } from '@/api/framework/system/dept'
import { getLevel } from '@/api/framework/system/role'
import { parseTime } from '@/utils/index'
import eForm from './form'
import importUser from './importUser'
import updateUserPass from './updateUserPass'
export default {
  components: { eForm ,importUser,updateUserPass},
  mixins: [initData, initDict],
  data() {
    return {
      height: document.documentElement.clientHeight - 180 + 'px;', isAdd: false,
      delLoading: false, resetLoading: false, deptName: '', depts: [], deptId: null,importDept:{},
      downLoadUrl: process.env.BASE_API + '/api/downLoadUserTel',
      defaultProps: {
        id:'id',
        children: 'children',
        label: 'name'
      },
      expanded: ['1','14986188603464026668'],
      downloadLoading: false,
      queryTypeOptions: [
        { key: 'username', display_name: '账号' },
        { key: 'name', display_name: '姓名' }
      ],
      enabledTypeOptions: [
        { key: 'true', display_name: '激活' },
        { key: 'false', display_name: '封停' }
      ]
    }
  },
 created() {
   this.getDeptDatas()
   this.getRoleLevel()
   // this.$nextTick(() => {
   //   this.init()
   //   // 加载数据字典
   //   this.getDict('user_status')
   // })
 },
  mounted: function() {
    const that = this
    window.onresize = function temp() {
      that.height = document.documentElement.clientHeight - 180 + 'px;'
    }
  },
  watch: {
    data(newVal, oldVal) {
      newVal.forEach((item,key) => {
        item.roles.forEach((item1,key1) => {
          if(this.level<item1.level){
            item.show=false;
          }else{
            item.show=true;
          }
        });
      });
    }

  },
  methods: {
    parseTime,
    checkPermission,
    beforeInit() {
      this.url = 'api/users'
      const sort = 'id,desc'
      const query = this.query
      const type = query.type
      const value = query.value
      const enabled = query.enabled
      this.params = { page: this.page, size: this.size, sort: sort, deptId: this.deptId }
      if (type && value) { this.params[type] = value }
      if (enabled !== '' && enabled !== null) { this.params['enabled'] = enabled }
      return true
    },
    subDelete(id) {
      this.delLoading = true
      del(id).then(res => {
        this.delLoading = false
        this.$refs[id].doClose()
        this.dleChangePage()
        this.init()
        this.$notify({
          title: '删除成功',
          type: 'success',
          duration: 2500
        })
      }).catch(err => {
        this.delLoading = false
        this.$refs[id].doClose()
      })
    },
    getDeptDatas() {
      const sort = 'id,desc'
      const params = { sort: sort }
      if (this.deptName) { params['name'] = this.deptName }
      getDepts(params).then(res => {
        this.depts = res.content
      })
    },
    getRoleLevel() {
      getLevel().then(res => {
        this.level = res.level
        this.$nextTick(() => {
          this.init()
          // 加载数据字典
          this.getDict('user_status')
        })
      }).catch(err => {
      })
    },
    handleNodeClick(data) {
      if (data.pid === 0) {
        this.deptId = null
      } else {
        this.deptId = data.id
        this.importDept={
          deptId:data.id,
          deptName:data.label,
        }
      }
      this.init()
    },
    add() {
      this.isAdd = true
      this.$refs.form.getDepts()
      this.$refs.form.getRoles()
      this.$refs.form.getRoleLevel()
      this.$refs.form.dialog = true
    },
    // 导出
    download() {
      this.downloadLoading = true
      import('@/utils/export2Excel').then(excel => {
        const tHeader = ['ID', '用户名', '邮箱', '头像地址', '状态', '注册日期', '最后修改密码日期']
        const filterVal = ['id', 'username', 'email', 'avatar', 'enabled', 'createTime', 'lastPasswordResetTime']
        const data = this.formatJson(filterVal, this.data)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'table-list'
        })
        this.downloadLoading = false
      })
    },
    // 数据转换
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'createTime' || j === 'lastPasswordResetTime') {
          return parseTime(v[j])
        } else if (j === 'enabled') {
          return parseTime(v[j]) ? '启用' : '禁用'
        } else {
          return v[j]
        }
      }))
    },
    edit(data) {
      this.isAdd = false
      const _this = this.$refs.form
      _this.getRoles()
      _this.getDepts()
      _this.getRoleLevel()
      _this.roleIds = []
      _this.form = {
        id: data.id,
        username: data.username,
        phone: data.phone,
        name: data.name,
        deptName: data.deptName,
        //email: data.email,
        enabled: data.enabled.toString(),
        roles: [],
        dept: { id: data.dept.id },
        //job: { id: data.job.id },
      }
      data.roles.forEach(function(data, index) {
        _this.roleIds.push(data.id)
      })
      _this.deptId = data.dept.id
      //_this.jobId = data.job.id
      _this.getJobs(_this.deptId)
      _this.dialog = true
    },
    suspensionUser(id,enabled){
      this.$confirm('确定解封/封停本账号?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var obj={
          id:id,
          enabled:enabled
        }
        suspension(obj).then(res => {
          this.init()
          this.$message({
            type: 'success',
            message: '操作成功!'
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '操作失败!'
          })
        })
      }).catch(() => {
      })
    },
    reset(data) {
      this.resetLoading = true
      this.$confirm('确定重置[' + data.name + ']用户密码?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        reset(data.username).then(res => {
          if (res) {
            this.$message({
              type: 'success',
              message: '重置成功!'
            })
          } else {
            this.$message({
              type: 'info',
              message: '重置失败!'
            })
          }
        }).catch(err => {

        })
        this.resetLoading = false
      }).catch(() => {
        this.resetLoading = false
      })
    },
    toImport(){
      if(this.deptId==null){
        this.$message({
          type: 'success',
          message: '请选择部门!'
        })
        return;
      }
      this.$refs.importForm.visible = true
    },
    downloadTemp(){
      window.location.href = this.downLoadUrl
    },
    upUserPass(data){
      this.$refs.updateUserFrom.dialog=true
      this.$refs.updateUserFrom.form.userName=data.username;
    }
  }
}
</script>

<style scoped>
  .bs-Tree{
    overflow: auto;
    height: calc(100vh - 140px);
    border-right: 1px solid #e0e0e0;
    background: #fafafa;
  }
</style>
